package xyz.jiang.common.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import xyz.jiang.common.enums.Sex;
import xyz.jiang.common.exceptions.GraceException;
import xyz.jiang.common.grace.result.GraceJSONResult;
import xyz.jiang.common.grace.result.ResponseStatusEnum;
import xyz.jiang.common.mapper.UsersMapper;
import xyz.jiang.common.pojo.dto.UsersDTO;
import xyz.jiang.common.pojo.entity.Users;
import xyz.jiang.common.pojo.vo.UsersVO;
import xyz.jiang.common.service.IUsersService;
import xyz.jiang.common.utils.RedisUtils;
import xyz.jiang.common.utils.UserUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static xyz.jiang.common.constants.RedisConstants.REDIS_USER_WECHAT_NUM;
import static xyz.jiang.common.constants.SystemConstants.SYSTEM_CACHE;
import static xyz.jiang.common.constants.UserConstants.USER_CACHE;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 风间影月
 * @since 2025-04-25
 */
@Service
@Transactional
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Resource
    private UsersMapper usersMapper;

    @Override
    public Users queryMobileIfExist(String mobile) {
        return usersMapper.selectOne(new LambdaQueryWrapper<Users>()
                .eq(Users::getMobile, mobile));
    }

    @Override

    public Users createUsers(String mobile) {
        Users user = new Users();
        user.setMobile(mobile);

        String uuid = UUID.randomUUID().toString();
        String[] uuidStr = uuid.split("-");
        String wechatNum = "wx" + uuidStr[0] + uuidStr[1];
        user.setWechatNum(wechatNum);
        user.setSex(Sex.secret.type);
        user.setFace("");
        user.setNickname("nn");
        user.setRealName(mobile);
        user.setWechatNumImg("");
        user.setFriendCircleBg("");
        user.setEmail("");
        user.setBirthday(LocalDate.now());
        user.setCountry("中国");
        user.setProvince("");
        user.setCity("");
        user.setDistrict("");
        user.setCreatedTime(LocalDateTime.now());
        user.setUpdatedTime(LocalDateTime.now());
        usersMapper.insert(user);

        return user;
    }

    @Override
    public Users modifyUser(UsersDTO usersDTO) {

        Users users = new Users();

        String id = usersDTO.getId();
        if (StrUtil.isBlank(id)) {
            GraceException.display(ResponseStatusEnum.USER_INFO_UPDATED_ERROR);
        }
        // 校验微信号修改次数，一年只能改一次
        validateWechatNumChangeLimit(usersDTO.getWechatNum());
        BeanUtils.copyProperties(usersDTO,users);
        users.setUpdatedTime(LocalDateTime.now());

        usersMapper.updateById(users);

        //删除redis中的用户信息
        RedisUtils.delete(SYSTEM_CACHE + USER_CACHE + id);


        return users;
    }

    @Override
    public GraceJSONResult getUserInfo(String userId) {

        Users currentUser = UserUtils.getCurrentUser();
        System.out.println("========================currentUser:" + currentUser);


        if (StrUtil.isBlank(userId)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.USER_ID_IS_NULL_ERROR);
        }
        Users user = (Users) RedisUtils.get(SYSTEM_CACHE + USER_CACHE + userId);
        UsersVO usersVO = new UsersVO();
        if (!ObjectUtils.isEmpty(user)) {
            BeanUtils.copyProperties(user,usersVO);
            return GraceJSONResult.ok(usersVO);
        }
        Users users = usersMapper.selectById(userId);
        if(ObjectUtils.isEmpty(users)) {
             return GraceJSONResult.errorCustom(ResponseStatusEnum.USER_NOT_EXIST_ERROR);
        }
        // 存到redis缓存中
        RedisUtils.set(SYSTEM_CACHE + USER_CACHE + userId,users);

        BeanUtils.copyProperties(users,usersVO);
        return GraceJSONResult.ok(usersVO);
    }

    private void validateWechatNumChangeLimit(String wechatNum) {
        // 校验微信号修改次数，一年只能改一次
        if(StrUtil.isBlank(wechatNum)) {
            return;
        }
        String wechatNumCache = (String)RedisUtils.get(REDIS_USER_WECHAT_NUM + wechatNum);
        if(StrUtil.isEmpty(wechatNumCache)) {
            RedisUtils.set(REDIS_USER_WECHAT_NUM + wechatNum,wechatNum,365, TimeUnit.DAYS);
        } else {
            GraceException.display(ResponseStatusEnum.WECHAT_NUM_ALREADY_MODIFIED_ERROR);
        }
    }
}
